﻿$(function() {
//Declare variable
var  Code= $( "#Code" ),
	FirstName = $( "#FirstName" ),
	LastName = $( "#LastName" ),
	Birthday = $( "#Birthday" ),
	Address=$("#Address"),
	Telephone=$("#Telephone"),
	CardNo=$("#CardNo"),
	Amount=$("#Amount"),
	allFields = $( [] ).add( Code )
						.add(FirstName)
						.add(LastName)
						.add(Birthday)
						.add(Address)
						.add(Telephone)
						,
	SmartFields=$([]).add(CardNo)
					.add(Amount)
					,
	tips = $( ".validateTips" ),
	button_name="",
	url="a_creditsale.php", 
	ID="",
	AddTitle="Add Payment",	
	EditTitle="Update Customer",	
	rowSelect="",
	list={};
		
		if  ($("#cboBranch").length > 0 ){
			$.get('a_stock.php', {"c":"b"},function(data){
				//alert(data);
				$.each(eval('('+data+')'), function(index, text) {
					$("#cboBranch").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			});	
			$("#cboBranch").append($('<option></option>').val(0).html('All'));
		}		
			
		//load first page
		LoadData(1,true);
		
		$("#pAmount").numeric();
		
		$("#btnAddPayment").button({
			icons:{
			 primary: "ui-icon-circle-plus"
			}
		});	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='9' class='search-background'>"
						+"<label><img src='images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};		
				
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		

		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 550,
			width: 600,
			zIndex:9999,
			modal: true,
			open: function() { 
				 $("#pAmount").val("");
				 $("#pAmount").focus();
				 $( "#tbPayHistory tbody tr" ).remove();
				 $("#PayCash").attr('checked','checked');
				 $("#tr_cardName").hide();
				 $("#txtCardNo").val('');
			},
			close: function() {
				$( "#tbPayHistory tbody tr" ).remove();
				$("#pAmount").val("");
				var totalAmt=0;
				for (prop in list) {
					totalAmt += parseFloat(list[prop]);
				  }		 
				if (totalAmt > 0) {
					newwindow=window.open('cs_print.php?i='+ID+'&a='+totalAmt,'','height=450px,width=350px');
					if (window.focus) {newwindow.focus()}	
				}
				ID="";				
				list={};
			}
		});
		function setValue(obj){
			$("#name").val(obj.eq(3).html());
			$("#tAmount").val(obj.eq(6).html());
			$("#rAmount").val(obj.eq(8).html());
			var remain= new Number(obj.eq(8).html().replace(',','').replace(',',''));
			//if (remain==0) {
			//	$(".tr_payment").hide();
			//}
			 ID=obj.eq(1).html();
			
			var dataSet={'id':ID,'m':'detail'};  
			//alert(id);
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					//	alert(data);
					var obj=eval('('+data+')');
					
					$("#tbPayHistory tbody:first" ).prepend( obj['html'] ); 
					$("#iCount").attr('innerHTML',obj['rows']);	
					$("#dlgTotalPay").attr('innerHTML',obj['paytoal']);	
					
				}
			});
		}
		
		// Set value from control to array 
		function getValue(){
			var o = {};
			//get name and value control 
			$( "#dialog-form" ).find('input').each(function(){
				if (o[$(this).attr('id')]) {
					if (!o[$(this).attr('id')].push) {
						o[$(this).attr('id')] = [o[$(this).attr('id')]];
					}
					o[$(this).attr('id')].push($(this).val() || '');
				} else {
					o[$(this).attr('id')] = $(this).val() || '';
				}
			});
			//Address 
			var _address = $( "#dialog-form" ).find('textarea').eq(0);
			o[_address.attr('id')] = _address.val() || '';
			
			return o;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( $("#pAmount"), "Payment Amount",1);
			//check pay more than remain or not
			var remain= new Number($("#rAmount").val().replace(',',''));
			var pay=$("#pAmount").val();
			if (isNaN(pay)){
				pay=0;
			}
			
			if ( parseFloat(pay) > remain){
				$("#pAmount").addClass( "ui-state-error" );
				updateTips( "Payment Amount more than Remain Amount.!!" );
				return bValid && false;
			}else{
				$("#pAmount").removeClass("ui-state-error" );
				return bValid && true;
			}
			
			
		}
		function CommaFormatted(amount)
		{
		 
			var delimiter = ","; // replace comma if desired
			var a = amount.split('.',2)
			var d = a[1];
			var i = parseInt(a[0]);
			if(isNaN(i)) { return ''; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			var n = new String(i);
			var a = [];
			while(n.length > 3)
			{
				var nn = n.substr(n.length-3);
				a.unshift(nn);
				n = n.substr(0,n.length-3);
			}
			if(n.length > 0) { a.unshift(n); }
			n = a.join(delimiter);
			if(d.length < 1) { amount = n; }
			else { amount = n + '.' + d; }
			amount = minus + amount;
			return amount;
		}
		function calulateAmount(payAmt){
				var amt=payAmt;
			 
				var totalPay=parseFloat( $("#dlgTotalPay").attr('innerHTML').replace(',','') );	
				var remain= parseFloat($("#rAmount").val().replace(',','').replace(',',''));
				var totalAmt= parseFloat($("#tAmount").val().replace(',','').replace(',',''));

				if (isNaN(amt) || amt==""){
					amt=0;
				}
				
				if (totalAmt -totalPay-parseFloat(amt) >=0){
					var t= new Number( totalAmt -totalPay-parseFloat(amt) );
					$("#rAmount").val(CommaFormatted(t.toFixed(2)));
				}
		}
		
		$("input:radio[name='PayType']").click(function(){
			var vPayType=$("input:radio[name='PayType']:checked").val();
			if (vPayType=="1"){
				$("#tr_cardName").hide().fadeOut('slow');
			}else  if (vPayType=="2"){
				$("#tr_cardName").show().fadeIn('slow');
				$("#lblcardNo").attr('innerHTML','Card No. :');
			}else if (vPayType=="3"){
				$("#tr_cardName").show().fadeIn('slow');	
				$("#lblcardNo").attr('innerHTML','Smart Purse No. :');
			}
		});
		//On blur event
		//$("#pAmount").keyup(function(){
		//	calulateAmount($(this).val());
		//});
		//Add Button
		$("#btnAddPayment").live('click',function(){
			if (ID ==""){
				 $( "#dialog-form" ).dialog( "close" );
			}
			
			if (checkRequireControl()){
				var type=$("input:radio[name='PayType']:checked").val(); 
				var card=$("#txtCardNo").val(); 
				
				var amount=$("#pAmount").val();	
				
				if (!(isNaN(amount))){
				
					calulateAmount(amount);
					
					$( "#tbPayHistory tbody tr" ).remove().fadeOut('200');
					$.post(url,  {'m':'add','id':ID,'amt':amount,'t':type,'c':card} , function(data){
						var obj=eval("("+data+")");

						$("#tbPayHistory tbody:first" ).prepend( obj['html'] ); 
						$("#iCount").attr('innerHTML',obj['rows']);	
						$("#dlgTotalPay").attr('innerHTML',obj['paytoal']);	
						
						list[obj['csid']]=amount;
						//Update amount to main screen.
						
						rowSelect.find("td").eq(5).html(obj['paydate']);
						rowSelect.find("td").eq(7).html(obj['paytoal']);
						rowSelect.find("td").eq(8).html($("#rAmount").val());
						if ( parseInt($("#rAmount").val()) ==0){
							rowSelect.find("td").eq(8).css('color','#666');
						}
					 });
					 $("#pAmount").val("");	
				}else{
					alert("Input payment amount incorrect!!");
				}
			}
			return false;
			
		});
		
		//Remove Button
		$("#btnRemove").live('click',function(){
				//get id from table
				var cid=$(this).parent().parent().find("td").eq(1).html();
				var re_Amt=$(this).parent().parent().find("td").eq(6).html().replace(',','').replace(',','');
				
				delete list[cid];
				
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						$.post(url,  {'m':'del','id':ID,'cid':cid,'amt':re_Amt} , function(data){
							
							var obj=eval("("+data+")");
							//remove row
							$( "#tbPayHistory tbody tr" ).remove().fadeOut('slow');
							// insert new 
							$("#tbPayHistory tbody:first" ).prepend( obj['html'] ).fadeIn('slow'); 
							$("#iCount").attr('innerHTML',obj['rows']);	
							$("#dlgTotalPay").attr('innerHTML',obj['paytoal']);	
							
							calulateAmount(0)
							//Update amount to main screen.
							rowSelect.find("td").eq(7).html(obj['paytoal']);
							rowSelect.find("td").eq(8).html($("#rAmount").val());
							
							if ( parseInt($("#rAmount").val())> 0){
								rowSelect.find("td").eq(8).css('color','red');
							}
						 });
						$( this ).dialog( "close" );
 
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
		});
		
		$( ".btnPay" ).live('click',function() {
			rowSelect = $(this).parent().parent();
			setValue(rowSelect.find("td"));
			
			$("#dialog-form").dialog({'title':AddTitle});
			$( "#dialog-form" ).dialog( "open" );
			$( "#dialog-form" ).dialog( "option","buttons",{
				"Close":function(){
					rowSelect="";
					$( this ).dialog( "close" );
				}
			});
		});

	$("#btnSearch").click(function(){
		LoadData(1,true);
		 
	});
	
	$("#btnBack").live('click',function(){
		//alert('d');
		$("#Act").submit();
		//history.back(-1);
	});
	function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			
			var branch=0;
			
			if ($("#cboBranch").length>0)
				branch=$("#cboBranch").val();		
				
			var dataSet={'m':'search'
						,'code':$("#txtCustCode").val()
						,'name':$("#txtCustName").val()
						,'status':$("#cboStatus").val()
						,'barnchid':branch
						,'page':page
						};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
			   //alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				 
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
					//set page
				if (b){
 
					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}					
					 
				}
				//$("#"+page).css({'background-color' : '#006699'});
			 });
		}
 
			
	
	function setPaging(iTotal){
				 $("#paging_btn").paginate({
				count 		: iTotal,
				start 		: 1,
				display     : 10,
				border					: false,
				text_color  			: '#888',
				background_color    	: '#EEE',	
				text_hover_color  		: 'blue',
				background_hover_color	: '#CFCFCF',
				mouse					: 'press',
				onChange     			: function(page){
											LoadData(page,false);
										  }
			});
		}
});
	